'use strict';

let fs=require('fs');
let path=require('path');
let router=require('koa-router')();

function getContronllerFiles(defaultDir){
    let files=fs.readdirSync(defaultDir);
    return files.filter((name)=>{
        return name.endsWith('.js') && name!=='index.js';
    });


}

function registerContronllerFiles(files,currentPath){
    files.forEach((item)=>{
        let tmpPath=path.join(currentPath,item);

        let routerObj=require(tmpPath);
        for (let r in routerObj){
            let type=routerObj[r][0];
            let fn=routerObj[r][1];
            if(type==='get'){
                router.get(r,fn);
            }else if(type==='post'){
                router.post(r,fn);
            }

        }

    });


}

module.exports=function(dir){
    let defaultDir=dir || './controllers';
    let root=path.resolve('.');
    let fullPath=path.join(root,defaultDir);
    let files=getContronllerFiles(fullPath);
    registerContronllerFiles(files,fullPath);
    return router.routes();

}
